#!/bin/sh
#desc:Control board drivers

CFGPATH="/etc/opendomo/control"
CTRLPATH="/var/opendomo/control"
PID="/var/run/odcontrol.pid"

if test `whoami` == "root"; then
	chown admin /etc/opendomo/control/
	#chown admin /var/run/ # OBSOLETE: it's done in "/etc/init.d/mount"
fi


start(){
  # Omitimos los archivos que no sean ".conf"
  for i in $CFGPATH/*.conf; do
	if test -f $i; then
		# 1. Cargamos configuración
		. $i
		# 2. Lanzamos el driver
		BINARY="/usr/bin/$driver"
		if test -x $BINARY; then
			if test `whoami` == "root"; then
				touch /var/log/odcontrol.log && chown admin /var/log/odcontrol.log 2>/dev/null
				su -c "$BINARY -d $device -p $dirname -r $refresh $params \
						>>/var/log/odcontrol.log 2>/dev/null" admin &
			else
				$BINARY -d $device -p $dirname -r $refresh $params \
						>>/var/log/odcontrol.log 2>/dev/null &
			fi		
			echo -n "($dirname)"
			#echo $NAME > $DIRNAME/desc
		else
			echo -n "($dirname failed)"
		fi
	fi
  done

  touch $PID
  chown admin $PID 2>/dev/null
  chmod g+rw $PID 2>/dev/null
}

stop(){
  echo -n "Stopping controllers..."
  for i in $CFGPATH/*.conf; do
	if test -f $i; then
		# 1.Cargamos configuración
		. $i
		# 2.Matamos el driver
		killall $driver 2>/dev/null

		# Remove directory
		rm -fr $CTRLPATH/$dirname
		rm -fr $CTRLPATH/ODC*
		#rm -fr $CFGPATH/domino_*
	fi

  done
  rm /var/opendomo/domino_devices.conf 2>/dev/null
  rm -fr $PID
}


case "$1" in
	start)
		echo -n "Starting controllers..."
		if test -f $PID; then
			echo -n "(already started)"
			exit 2
		else
			start
		fi
	;;
	stop)
		echo -n "Stopping controllers..."
		stop
	;;
	status)
		if test -f $PID; then
			echo "The service is running"
			exit 0
		else
			echo "Service not started"
			exit 1
		fi
	;;
	reload)
		echo -n "Reloading controllers..."
		#TODO: Send -HUP signal
	;;
	restart)
		echo -n "Restarting controllers..."
		stop
		start
	;;
	*)
		echo $"Usage: $0 {start|stop|restart|status}"
		exit 1
esac
